using UnityEngine;
using System.Collections;

// preso da http://www.unifycommunity.com/wiki/index.php?title=FramesPerSecond 

public class SV_FPSCounter : MonoBehaviour 
{

// Attach this to a GUIText to make a frames/second indicator.
//
// It calculates frames/second over each updateInterval,
// so the display does not keep changing wildly.
//
// It is also fairly accurate at very low FPS counts (<10).
// We do this not by simply counting frames per interval, but
// by accumulating FPS for each frame. This way we end up with
// correct overall FPS even if the interval renders something like
// 5.5 frames.
 
	
	#region Members
	
	public  float		m_fUpdateInterval = 0.5F;
	 
	private float		m_fAccum   = 0; // FPS accumulated over the interval
	private int			m_iFrames  = 0; // Frames drawn over the interval
	private float		m_fTimeleft; // Left time for current interval
	private float		m_fFpsToDraw = 0.0f;
	
	float				m_fTextWidth = 60.0f;
	float				m_fTextHeight = 20.0f;
	
	float				m_fTextOffsetWidth = 0.0f;
	float				m_fTextOffsetHeight = 0.0f;
	
	
	#endregion
	
	
	public void Awake()
	{
		m_fTextOffsetWidth = m_fTextWidth*1.1f;
		m_fTextOffsetHeight = m_fTextHeight*1.2f;
	}
	 
	public void Start()
	{
	    m_fTimeleft = m_fUpdateInterval;
	}
	 
	public void Update()
	{
		if(Time.timeScale > 0 && Time.deltaTime > 0) // aggiunta di maico per evitare division by zero quando timescale = 0
		{
			m_fTimeleft -= Time.deltaTime;
			m_fAccum += Time.timeScale/Time.deltaTime;
			++m_iFrames;
		    
			// Interval ended - update GUI text and start new interval
			if( m_fTimeleft <= 0.0 )
			{
				// display two fractional digits (f2 format)
				m_fFpsToDraw = m_fAccum/m_iFrames;
				if(m_fFpsToDraw >= 30)
				{
					m_fTimeleft = m_fUpdateInterval;
					m_fAccum = 0.0F;
					m_iFrames = 0;
				}
			}
		}		
	}
	
	public void OnGUI()
	{
		//float fXRatio = Screen.width/1920.0f;
		float fYRatio = Screen.height/1080.0f;

		GUI.TextField(new Rect((Screen.width-m_fTextWidth)-(m_fTextOffsetWidth*fYRatio), (Screen.height-m_fTextHeight)-(m_fTextOffsetHeight*fYRatio), m_fTextWidth, m_fTextHeight), m_fFpsToDraw.ToString("f2"));
	}
}